package com.nuanshui.framework.lang;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

public class CollectionUtil {

	/**
	 * 
	 * @Title: filterCollection
	 * @Description: TODO
	 * @author 郭浩
	 * @param @param collection 要过滤的集合
	 * @param @param filter 过滤条件
	 * @param @return
	 * @return Integer 过滤后集合的大小
	 * @throws
	 * @date 2014-7-10 下午3:38:07
	 * @version V1.0
	 */
	public static <N extends Object> Integer filterCollection(
			final Collection<N> collection, final CollectionFilter<N> filter) {
		Iterator<N> iterator = collection.iterator();
		if (collection.isEmpty()) {
			return collection.size();
		}
		while (iterator.hasNext()) {
			if (filter.filter(iterator.next())) {
				iterator.remove();
			}
		}
		return collection.size();
	}

	public static <K, V extends Object> void filterMap(final Map<K, V> map,
			final MapFilter<? super K, ? super V> filter) {
		Iterator<K> keys = map.keySet().iterator();
		while (keys.hasNext()) {
			K key = keys.next();
			V value = map.get(key);
			if (filter.filter(key, value)) {
				keys.remove();
			}
		}

	}

	/**
	 * 
	 * @ClassName: MapFilter
	 * @Description: TODO map过滤
	 * @author 郭浩
	 * @date 2014-7-10 下午3:37:47
	 * 
	 * @param <K>
	 * @param <V>
	 */
	public interface MapFilter<K, V> {

		boolean filter(K key, V value);

	}

	public interface CollectionFilter<T> {

		boolean filter(T t);

	}

}
